<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item prop="unknown" style="width: 360px;margin-top: 30px;" class="search-input-wrap">
        <el-input placeholder="搜索内容" v-model="queryParams.unknown" class="input-with-select" :style="{ width: '100%' }">
          <el-select v-model="select" slot="prepend" placeholder="请选择" :style="{ width: '100px' }">
            <el-option label="付款单号" value="1" />
            <el-option label="申请单号" value="2" />
            <el-option label="采购单号" value="3" />
            <el-option label="关联单号" value="4" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="handleQuery"/>
        </el-input>
      </el-form-item>

      <el-form-item label="供应商" style="width: 220px">
        <treeselect v-model="queryParams.vendorId" :options="vendorOptions" :show-count="true" placeholder="请输入供应商"
          style="width: 100%" />
      </el-form-item>

      <el-form-item label="制单日期" style="width: 350px">
        <el-date-picker v-model="queryParams.createTime" value-format="yyyy-MM-dd" type="daterange" align="right"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
      </el-form-item>

      <el-form-item label="付款单状态" style="width: 180px">
        <el-select v-model="queryParams.paymentMasterStatus" placeholder="请选择付款单状态" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.payment_master_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态" style="width: 180px">
        <el-select v-model="queryParams.deleteStatus" placeholder="请选择订单状态" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.tb_delete_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item style="margin-top: 30px;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" :disabled="multiple" @click="sumbitOnlyVoucher"
          v-hasPermi="['finance:paymentVoucher:approved']">批量核准（单独付款）</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" :disabled="multiple" @click="sumbitVoucher"
          v-hasPermi="['finance:paymentVoucher:approved']">核准（合并付款）</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-finished" size="mini" :disabled="multiple" @click="buttonUpload"
          v-hasPermi="['finance:paymentVoucher:posting']">上传水单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-magic-stick" size="mini" :disabled="multiple"
          @click="buttonUploadNotPic" v-hasPermi="['finance:paymentVoucher:posting']">批量标记已付款</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-close" size="mini" :disabled="multiple" @click="handleReject"
          v-hasPermi="['finance:paymentVoucher:reject']">批量驳回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-key" size="mini" :disabled="multiple" @click="handleIslock"
          v-hasPermi="['finance:paymentVoucher:taglock']">锁定付款</el-button>
      </el-col>
      <span v-if="selectTotalAmount > 0" style="margin-left: 5%;font-size:16px">
        汇总金额：<span style="color:green;font-weight:800">{{ selectTotalAmount.toFixed(2) }}</span>
      </span>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPaymentMasterList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PaymentVoucherList" ref="parentTable" row-key="paymentMasterId"
      @selection-change="handleParentSelectionChange" @expand-change="handleExpandChange">

      <el-table-column type="selection" width="55" align="center" />

      <el-table-column align="center" width="20" type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.paymentVouchers" :ref="'nestedTable-' + scope.row.paymentMasterId"
            row-key="paymentRequestCode"
            @selection-change="(childSelection) => childSelectionChange(scope.row, childSelection)">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="申请单号" align="center" prop="paymentRequestCode" />
            <el-table-column label="付款单类型" align="center" prop="paymentVoucherType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.payment_voucher_type" :value="scope.row.paymentVoucherType" />
              </template>
            </el-table-column>
            <el-table-column label="采购单号" align="center" prop="ordersNumber" />
            <el-table-column label="申请金额" align="center">
              <template v-slot="scope">
                {{ scope.row.paymentVoucherAmountDue.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="核准" align="center" width="155">
              <template slot-scope="scope">
                {{ scope.row.approvedBy }}<br />{{
                  scope.row.approvedTime
                }}
              </template>
            </el-table-column>
            <el-table-column label="关联申请单号" align="center" prop="relatedCodes" v-if="1 == 2">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.relatedCodes" placement="top">
                  <span v-if="scope.row.relatedCodes" :title="scope.row.relatedCodes">
                    {{ scope.row.relatedCodes.slice(0, 32) }}
                    <span v-if="scope.row.relatedCodes.length > 32">...</span>
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="付款单状态" align="center" prop="paymentVoucherStatus" width="120px">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.payment_voucher_status" :value="scope.row.paymentVoucherStatus" />
              </template>
            </el-table-column>
            <el-table-column label="水单图片" prop="waterBillImg" align="center">
              <template slot-scope="scope">
                <div class="image-container">
                  <image-preview v-if="scope.row.waterBillImg" :src="scope.row.waterBillImg" :width="50" :height="50"
                    class="image-item" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" prop="deleteStatus" width="100px">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.tb_delete_status" :value="scope.row.deleteStatus" />
              </template>
            </el-table-column>
            <el-table-column label="撤回备注" align="center" prop="revokeRemark">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.revokeRemark">
                  <span>
                    {{ scope.row.revokeRemark && scope.row.revokeRemark.length > 5 ? scope.row.revokeRemark.slice(0, 5)
                      + '...' : (scope.row.revokeRemark || '-') }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
              <template slot-scope="scope">
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
                  'finance:paymentVoucher:list',
                  'finance:paymentVoucher:approved',
                  'finance:paymentVoucher:posting',
                ]">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="approvedQuash" icon="el-icon-check"
                      v-hasPermi="['finance:paymentVoucher:approved']"
                      v-if="scope.row.paymentVoucherStatus == 0 && Number(scope.row.deleteStatus || -1) === 0">核准</el-dropdown-item>
                    <el-dropdown-item command="rejectQuash" icon="el-icon-close"
                      v-hasPermi="['finance:paymentRequest:reject']"
                      v-if="scope.row.paymentVoucherStatus == 0 && Number(scope.row.deleteStatus || -1) === 0">驳回</el-dropdown-item>
                    <el-dropdown-item command="uploadQuash" icon="el-icon-finished"
                      v-hasPermi="['finance:paymentVoucher:posting']"
                      v-if="(scope.row.paymentVoucherStatus == 1 || scope.row.paymentVoucherStatus == 4) && Number(scope.row.deleteStatus || -1) === 0">上传水单</el-dropdown-item>
                    <el-dropdown-item command="detailQuash" icon="el-icon-document"
                      v-hasPermi="['product:PaymentRequestProcess:list']">详情</el-dropdown-item>
                    <el-dropdown-item command="LogQuash" icon="el-icon-s-operation">日志</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
            <el-table-column label="驳回备注" align="center" prop="rejectRemark" width="120px">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.rejectRemark">
                  <span>
                    {{ scope.row.rejectRemark && scope.row.rejectRemark.length > 5 ? scope.row.rejectRemark.slice(0, 5)
                      + '...' : (scope.row.rejectRemark || '-') }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="预付款备注" align="center" prop="paymentVoucherRemark" width="120px">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.paymentVoucherRemark">
                  <span>
                    {{ scope.row.paymentVoucherRemark && scope.row.paymentVoucherRemark.length > 5 ?
                      scope.row.paymentVoucherRemark.slice(0, 5)
                      + '...' : (scope.row.paymentVoucherRemark || '-') }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="付款单号" align="center" prop="paymentMasterCode" />
      <el-table-column label="制单" align="center">
        <template slot-scope="scope">
          {{ scope.row.createBy }}<br />{{
            scope.row.createTime
          }}
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="vendorName" />
      <el-table-column label="供应商类型" align="center" prop="vendorAttribute" :formatter="formatVendorAttribute" />
      <el-table-column label="银行卡号" align="center" prop="bankCards" />
      <el-table-column label="开户行" align="center" prop="accountBank" />
      <el-table-column label="开户人" align="center" prop="accountHolder" />
      <el-table-column label="申请金额" align="center" width="120px">
        <template v-slot="scope">
          {{ scope.row.amountDue.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="付款单状态" align="center" width="120px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_master_status" :value="scope.row.paymentMasterStatus" />
        </template>
      </el-table-column>
      <el-table-column label="货币" align="center" prop="monetaryName" width="100px" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getPaymentMasterList" />
    <!-- 付款单详情页 -->
    <el-dialog :title="titleQuery" :visible.sync="openQuery" width="1000px" append-to-body>
      <el-form ref="form" :data="detailData" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="申请单号:" prop="paymentRequestCode">
              {{ detailData.paymentRequestCode }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款类型:" prop="paymentVoucherType">
              {{ paymentVoucherTypeText }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商:" prop="vendorName">
              {{ detailData.vendorName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购单号:" prop="ordersNumber">
              {{ detailData.ordersNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请金额:" prop="paymentVoucherAmountDue">
              <span style="font-weight: bold; font-size: 16px; color: green">
                {{ detailData.paymentVoucherAmountDue }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货币:" prop="monetaryName">
              {{ detailData.monetaryName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款账号:" prop="bankCards">
              {{ detailData.bankCards }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单信息:">
              {{ detailData.createInfo }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款单状态:">
              <dict-tag :options="dict.type.payment_voucher_status" :value="detailData.paymentVoucherStatus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="核准信息:">
              {{ detailData.approvedBy }}
              {{
                parseTime(detailData.approvedTime, "{y}-{m}-{d} {hh}:{mm}:{ss}")
              }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="过账信息:">
              {{ detailData.postingBy }}
              {{
                parseTime(detailData.postingTime, "{y}-{m}-{d} {hh}:{mm}:{ss}")
              }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预付备注:" prop="requestRemark">
              <el-input v-model="detailData.paymentVoucherRemark"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驳回备注:" prop="rejectRemark">
              <el-input v-model="detailData.rejectRemark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="水单图片:" prop="waterBillImg" v-if="detailData.waterBillImg">
              <el-<image-preview :src="detailData.waterBillImg" style="width: 30%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeForm">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 上传水单 -->
    <el-dialog :title="titleUpload" :visible.sync="openUpload" width="600px" append-to-body @close="cancel">
      <el-table v-loading="loading" :data="waterReceiptRows">
        <el-table-column label="申请单号" align="center" prop="paymentRequestCode" />
        <el-table-column label="申请金额" align="center">
          <template v-slot="scope">
            {{ scope.row.paymentVoucherAmountDue.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="货币" align="center" prop="monetaryName" />
      </el-table>
      <!-- 总金额显示 -->
      <div style="margin-bottom: 15px; margin-top: 15px">
        总金额：<span style="font-weight: bold; font-size: 16px; color: green">{{ totalAmount.toFixed(2) }}</span>
      </div>
      <el-form ref="form" :model="formUpload" :rules="rules" label-width="80px">
        <el-upload class="upload-demo" ref="upload" :limit="1" accept=".jpg, .png" :action="upload.url"
          :headers="upload.headers" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
          :file-list="upload.fileList" list-type="picture" :auto-upload="false">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sumbitUpload" :loading="isSubmitting" :disabled="isSubmitting">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 日志记录 -->
    <el-dialog :visible.sync="openLog" width="1000px" append-to-body :close-on-click-modal="false" title="付款单日志">
      <el-table v-loading="logLoading" :data="paymentVoucherLogList" height="500px">
        <el-table-column label="申请单号" align="center" prop="paymentRequestCode" />
        <el-table-column label="操作" align="center" prop="logMessage" />
        <el-table-column label="备注" align="center" prop="logRemark" />
        <el-table-column label="操作人" align="center" prop="logBy" />
        <el-table-column label="操作时间" align="center">
          <template slot-scope="scope">
            {{ parseTime(scope.row.logTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="logTotals > 0" :total="logTotals" :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize" @pagination="getPaymentVoucherLogList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRequestLog">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 弹窗 -->
    <el-dialog title="提示" :visible.sync="rejectDialogVisible" width="350px" @close="resetRejectForm">
      <p>您确定将所选记录驳回吗？</p>

      <!-- 输入框：填写驳回原因 -->
      <el-form :model="rejectForm" :rules="rules" ref="rejectFormRef">
        <el-form-item label="驳回原因" prop="rejectRemark">
          <el-input type="textarea" placeholder="请输入驳回原因" v-model="rejectForm.rejectRemark" rows="3" />
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="sumbitReject" :loading="loading">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaymentVoucher, //数据列表
  approvedPaymentVoucher, //核准（合并付款）
  selectPaymentVoucherLogList, //日志
  rejectPaymentVoucher, //驳回
  uploadWaterBillImg, //上传水单
  tagLockPaymentVoucher,//标记锁定
  approvedPaymentVoucherOnly,//批量核准（单独付款）
} from "@/api/finance/paymentVoucher";
import { getSelectVendorTreeList } from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
export default {
  name: "paymentVoucher",
  dicts: [
    "payment_voucher_type",
    "payment_voucher_status",
    "tb_delete_status",
    "payment_voucher_taglock",
    "payment_master_status"
  ],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款单表格数据
      PaymentVoucherList: [],
      // 弹出层标题
      title: "",
      titleQuery: "",
      titleUpload: "",
      vendorOptions: [],
      // 是否显示弹出层
      open: false,
      openQuery: false,
      openUpload: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentVoucherStatus: null,
        createTime: this.getLastMonthRange(),
        vendorId: null,
        deleteStatus: '0'
      },
      // 表单参数
      form: {},
      formQuery: {},
      formUpload: {
        paymentVoucherId: [],
        waterBillImg: null,
      },
      // 表单校验
      rules: {},

      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      // 存储每个子表的选中数据
      selectedItems: {},
      selectedRows: [],
      //日志
      openLog: false,
      logLoading: false,
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,
      paymentVoucherLogList: [],
      // 控制弹窗显示
      rejectDialogVisible: false,
      rejectForm: {
        rejectRemark: "", // 驳回原因
        paymentVoucherIds: "",
      },
      select: "1",
      rules: {
        rejectRemark: [
          { required: true, message: "请填写驳回原因", trigger: "blur" },
        ],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              end.setTime(end.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      //水单信息
      waterReceiptRows: [],
      // 防止重复提交
      isSubmitting: false,
      detailData: [],
      selection: [],
      selectTotalAmount: 0, //汇总金额
      updatingSelection: false,
      selectedChildMap: {},
      formatVendorAttribute(row) {
        return row.vendorAttribute ==='0' ? '1688供应商' : '线下供应商';
      }
    };
  },
  created() {
    this.getPaymentMasterList();
    this.getVendor();
  },
  computed: {
    paymentVoucherTypeText() {
      const paymentVoucherTypes = {
        0: "采购应付款",
        1: "采购预付款",
      };
      return paymentVoucherTypes[this.detailData.paymentVoucherType] || "";
    },
    totalAmount() {
      // 动态计算总金额
      return this.waterReceiptRows.reduce(
        (sum, row) => sum + row.paymentVoucherAmountDue,
        0
      );
    },

  },
  methods: {
    /** 查询付款单列表 */
    getPaymentMasterList() {
      this.loading = true;
      const [startTime, endTime] = this.queryParams.createTime || [];
      const params = {
        ...this.queryParams,
        startTime,
        endTime,
      };
      delete params.createTime;
      listPaymentVoucher(params).then((response) => {
        this.PaymentVoucherList = response.rows;
        this.PaymentVoucherList.forEach((row) => {
          if (row.paymentVouchers && row.vendorName) {
            row.paymentVouchers.forEach((paymentVoucher) => {
              // paymentVoucher.vendorName = row.vendorName; // 将 vendorName 添加到子表每一项
              // paymentVoucher.deleteStatus = row.deleteStatus;
              // paymentVoucher.monetaryName = row.monetaryName;
              // paymentVoucher.bankCards = row.bankCards;
              // paymentVoucher.createInfo = row.createBy + " " + row.createTime;
            });
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        paymentId: null,
        paymentOrder: null,
        paymentType: null,
        advanceId: null,
        paymentApplicant: null,
        paymentApplicationDate: null,
        postingApplicant: null,
        postingApplicationDate: null,
        paymentStatus: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
      };
      this.formUpload = {
        paymentVoucherId: null,
        waterBillImg: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.select = this.select;
      this.getPaymentMasterList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      //this.$set(this.selectedItems, rowIndex, selectedRows);
      const allSelected = Object.values(this.selectedItems).flat();
      this.ids = allSelected.map((item) => item.paymentVoucherId);
      this.single = allSelected.length !== 1;
      this.multiple = !allSelected.length;
      this.selectedRows = allSelected;
      this.selection = allSelected;
      // 汇总金额
      this.selectTotalAmount = allSelected.reduce((sum, item) => {
        const amount = item.paymentVoucherAmountDue ?? 0;
        return sum + Number(amount);
      }, 0);

    },
    /** 父表多选事件：当父表某些行被选中/取消选中时触发 */
    handleExpandChange(row, expandedRows) {
      // expandedRows 是所有已展开的行
      const isExpanded = expandedRows.includes(row);
      if (!isExpanded) return; // 只在“展开”时处理

      this.$nextTick(() => {
        const nestedRef = this.$refs['nestedTable-' + row.paymentMasterId];
        const nestedTable = Array.isArray(nestedRef) ? nestedRef[0] : nestedRef;
        if (!nestedTable) return;

        // 如果父行本身是勾选状态 => 全选子行
        const isParentChecked = this.$refs.parentTable.selection.includes(row);
        if (isParentChecked) {
          nestedTable.clearSelection();
          nestedTable.data.forEach(child => {
            nestedTable.toggleRowSelection(child, true);
          });

        }
      });
    },
    handleParentSelectionChange(selectedRows) {
      this.selectedItems = {};
      selectedRows.forEach(row => {
        const rowIndex = this.PaymentVoucherList.findIndex(
          item => item.paymentMasterId === row.paymentMasterId
        );
        // 确保找到了对应的父行
        if (rowIndex !== -1) {
          // 直接用 row.paymentVouchers
          this.$set(this.selectedItems, rowIndex, row.paymentVouchers);
        }
      });

      this.handleSelectionChange();
      //this.handleSelectionChange();
      // 如果正在更新选择状态，直接返回，防止递归
      if (this.updatingSelection) return;

      // 标记正在更新
      this.updatingSelection = true;
      // 遍历所有父行
      this.PaymentVoucherList.forEach(row => {
        const isChecked = selectedRows.includes(row); // 是否被父表选中

        // 找到对应的子表引用
        // 注意：如果你给子表的 ref 是 nestedTable-xxx，
        // ElementUI里 this.$refs 可能是数组或对象，看你如何使用
        const nestedTableRef = this.$refs['nestedTable-' + row.paymentMasterId];
        // 如果使用 <el-table ref="xxx">，则 nestedTableRef 通常是一个数组
        const nestedTable = nestedTableRef && nestedTableRef[0]
          ? nestedTableRef[0]
          : nestedTableRef;

        if (!nestedTable) return; // 如果子表还没渲染，就跳过

        // 先清空子表勾选
        nestedTable.clearSelection();

        // 如果父行是勾选状态 => 全选子表

        if (isChecked) {
          nestedTable.data.forEach(child => {
            nestedTable.toggleRowSelection(child, true);
          });
        }
      });
      // 更新结束后，重置标志位
      this.updatingSelection = false;
    },

    /** 子表多选事件：当子表被选中/取消选中时触发 */
    childSelectionChange(parentRow, childSelection) {
      // 通过 paymentMasterId 找到父行在 PaymentVoucherList 中的索引
      const rowIndex = this.PaymentVoucherList.findIndex(
        item => item.paymentMasterId === parentRow.paymentMasterId
      );
      // 使用这个索引更新 selectedItems
      this.$set(this.selectedItems, rowIndex, childSelection);
      this.handleSelectionChange();


      if (this.updatingSelection) return;
      this.updatingSelection = true;

      const nestedTable = this.$refs[`nestedTable-${parentRow.paymentMasterId}`];
      if (!nestedTable) {
        this.updatingSelection = false;
        return;
      }
      // 如果子表全部选中，则父行选中
      if (childSelection.length === nestedTable.data.length) {
        this.$refs.parentTable.toggleRowSelection(parentRow, true);
      }
      // 如果子表全部取消，则父行也取消
      else if (childSelection.length === 0) {
        this.$refs.parentTable.toggleRowSelection(parentRow, false);
      }
      this.updatingSelection = false;
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    /** */
    closeForm() {
      this.openQuery = false;
    },
    checkIsDelete() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.warning("请先勾选订单");
        return false;
      }
      const validList = this.selection.every(item => Number(item.deleteStatus) === 0);
      if (!validList) {
        this.$message.warning("请选择订单状态为【正常】");
        return false;
      }
      return true;
    },
    /**核准按钮 */
    sumbitVoucher(selectRow, isBoolean) {

      if (!isBoolean) {
        if (!this.checkIsDelete()) {
          return;
        }
        if (!this.checkSelectVoucher("核准", true)) {
          return;
        }
        if (!this.checkStatus("核准")) {
          return;
        }
      }

      const paymentVoucherIds = selectRow.paymentVoucherId || this.ids;

      this.$modal
        .confirm("您确认所选数据将核准吗？")
        .then(() => {
          return approvedPaymentVoucher(paymentVoucherIds);
        })
        .then(() => {
          this.resetData();
          this.getPaymentMasterList();
          this.$modal.msgSuccess("核准成功!");
        })
        .catch(() => { });
    },
    //批量核准（单独付款）
    sumbitOnlyVoucher() {
      if (!this.checkIsDelete()) {
        return;
      }
      // if (!this.checkSelectVoucher("批量核准（单独付款）", false)) {
      //   return;
      // }
      if (!this.checkStatus("批量核准（单独付款）")) {
        return;
      }
      const paymentVoucherIds = this.ids;
      this.$modal
        .confirm("您确认所选数据将核准吗？")
        .then(() => {
          return approvedPaymentVoucherOnly(paymentVoucherIds);
        })
        .then(() => {
          this.resetData();
          this.getPaymentMasterList();
          this.$modal.msgSuccess("批量核准（单独付款）成功!");
        })
        .catch(() => { });
    },
    resetData() {
      this.ids = [];
      this.selectedRows = [];
      this.selection = [];
      this.selectedItems = {};
    },
    /**驳回 */
    handleReject(selectRow, isBoolean) {

      if (!this.checkIsDelete()) {
        return;
      }

      if (!isBoolean) {
        if (!this.checkStatus("批量驳回")) {
          return;
        }
      }
      this.rejectDialogVisible = true;
      this.rejectForm.paymentVoucherIds =
        selectRow.paymentVoucherId || this.ids;
    },
    sumbitReject() {
      // 表单校验
      this.$refs.rejectFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 模拟接口请求
          setTimeout(() => {
            rejectPaymentVoucher(
              this.rejectForm.paymentVoucherIds,
              this.rejectForm.rejectRemark
            ).then((response) => {
              this.loading = false;
              this.rejectDialogVisible = false;
              this.getPaymentMasterList();
              this.resetData();
              // 提示成功
              this.$message.success("申请已驳回！");
            });
          }, 300);
        }
      });
    },
    buttonUpload(selectRow) {

      if (!this.checkIsDelete()) {
        return;
      }

      if (!this.checkVoucher("批量付款")) {
        return;
      }
      this.waterReceiptRows = this.selectedRows;
      this.handleUpload(selectRow);
    },
    showUpload(selectRow, isBoolean) {
      if (!isBoolean) {
        if (!this.checkVoucher("批量付款")) {
          return;
        }
      }
      this.waterReceiptRows = Array.isArray(selectRow)
        ? selectRow
        : [selectRow];
      this.handleUpload(selectRow);
    },
    /** 上传水单 */
    handleUpload(selectRow) {
      this.titleUpload = "上传水单";
      this.openUpload = true;
      let paymentVoucherIds = selectRow.paymentVoucherId || this.ids;
      // 保证为数组格式（即使只选中了一个）
      if (!Array.isArray(paymentVoucherIds)) {
        paymentVoucherIds = [paymentVoucherIds]
      }
      this.formUpload.paymentVoucherId = paymentVoucherIds;
      this.formUpload.hasWaterBill = true;
    },
    /** 上传水单确认按钮 */
    async sumbitUpload() {
      if (this.isSubmitting) {
        this.$message.error("数据正在处理，请勿重复提交！");
        return;
      }

      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.isSubmitting = true; // 设置提交状态
          try {
            // 手动触发上传，并等待完成
            await this.uploadFile();
            // 确保上传完成后再提交
            if (
              this.formUpload.paymentVoucherId &&
              this.formUpload.waterBillImg
            ) {
              await uploadWaterBillImg(this.formUpload);
              this.resetData();
              this.$modal.msgSuccess("上传水单成功！");
              this.openUpload = false;
              this.getPaymentMasterList();
            }
          } catch (error) {
            //this.$message.error("上传失败，请重试！");
          } finally {
            this.isSubmitting = false; // 重置提交状态
          }
        }
      });
    },
    uploadFile() {
      return new Promise((resolve, reject) => {
        this.$refs.upload.submit();
        this.$once("upload-success", resolve); // 上传成功后 resolve
        this.$once("upload-failed", reject); // 上传失败后 reject
      });
    },

    //批量标记已付款（无水单）
    async buttonUploadNotPic() {
      //校验是否都是正常付款单
      if (!this.checkIsDelete()) {
        return;
      }
      //校验是否相同供应商、货币单位、未过账状态
      const hasNonReviewStatus = this.selectedRows.every(
        (row) => row.paymentVoucherStatus == "1"
      );
      if (!hasNonReviewStatus) {
        this.$message.error("批量标记已付款，请选择【未过账】的数据");
        return false;
      }
      //校验是否为1688供应商
      const hasSameVendorAttribute = this.selectedRows.every(
        (row) => row.vendorAttribute === '0'
      );
      if (!hasSameVendorAttribute) {
        this.$message.error("批量标记已付款，请选择供应商类型为【1688供应商】的付款单");
        return;
      }
      this.formUpload.paymentVoucherId = this.ids;
      this.formUpload.hasWaterBill = false;
      if (this.isSubmitting) {
        this.$message.error("数据正在处理，请勿重复提交！");
        return;
      }
      this.isSubmitting = true;

      try {
        await uploadWaterBillImg(this.formUpload);
        // 如果有成功提示或后续操作，可以放这里
        this.resetData();
        this.$message.success("操作成功！");
        this.getPaymentMasterList();
      } catch (error) {
        // 如果 uploadNotWaterBillImg 抛错，可以提示失败信息
      } finally {
        // 始终重置提交状态
        this.isSubmitting = false;
      }
    },

    showDetail(row) {
      this.detailData = row;
      this.openQuery = true;
      this.titleQuery = "付款单查看";
    },
    showLog(row) {
      this.openLog = true;
      this.logParam.paymentVoucherId = row.paymentVoucherId;
      this.getPaymentVoucherLogList();
    },
    //查询记录
    getPaymentVoucherLogList() {
      this.logLoading = true;
      selectPaymentVoucherLogList(this.logParam).then((response) => {
        this.paymentVoucherLogList = response.rows;
        this.logTotals = response.rows.length;
        this.logLoading = false;
      });
    },
    //关闭日志
    cancelRequestLog() {
      this.openLog = false;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "approvedQuash":
          this.sumbitVoucher(row, true);
          break;
        case "rejectQuash":
          this.handleReject(row, true);
          break;
        case "uploadQuash":
          this.showUpload(row, true);
          break;
        case "detailQuash":
          this.showDetail(row);
          break;
        case "LogQuash":
          this.showLog(row);
          break;
        default:
          break;
      }
    },
    resetRejectForm() {
      this.rejectForm = {
        rejectRemark: "",
        paymentVoucherIds: [],
      };
      // 使用 $nextTick 确保在 DOM 更新后再执行重置
      this.$nextTick(() => {
        // 重置表单校验状态
        this.$refs.rejectFormRef.clearValidate();
      });
    },
    getLastMonthRange() {
      const endDate = new Date(); // 当前时间
      const startDate = new Date();
      startDate.setMonth(startDate.getMonth() - 3); // 设置为三个月
      return [startDate, endDate];
    },
    //检查是否都是审核中
    checkStatus(title) {
      const hasNonPaymentVoucherStatus = this.selectedRows.some(
        (row) => row.paymentVoucherStatus !== "0"
      );
      if (hasNonPaymentVoucherStatus) {
        this.$message.error(title + "，请选择【未核准】的数据");
        return false;
      }
      return true;
    },
    //检查是否相同供应商
    checkSelectVoucher(title, isChecked) {
      const hasSameVendor = this.selectedRows.every(
        (row) => row.vendorName === this.selectedRows[0]?.vendorName
      );
      if (!hasSameVendor) {
        this.$message.error(title + "，请选择相同供应商");
        return false;
      }

      const hasSameMonetaryName = this.selectedRows.every(
        (row) => row.monetaryName === this.selectedRows[0]?.monetaryName
      );
      if (!hasSameMonetaryName && isChecked) {
        this.$message.error(title + "，请选择相同货币");
        return false;
      }
      return true;
    },
    //检查是否同一供应商,检查是否都是未过账
    checkVoucher(title) {
      const hasSameVendor = this.selectedRows.every(
        (row) => row.vendorName === this.selectedRows[0]?.vendorName
      );
      if (!hasSameVendor) {
        this.$message.error(title + "，请选择相同供应商");
        return false;
      }

      const hasSameMonetaryName = this.selectedRows.every(
        (row) => row.monetaryName === this.selectedRows[0]?.monetaryName
      );
      if (!hasSameMonetaryName) {
        this.$message.error(title + "，请选择相同货币");
        return false;
      }

      const hasNonReviewStatus = this.selectedRows.every(
        (row) => row.paymentVoucherStatus == "1"
      );
      if (!hasNonReviewStatus) {
        this.$message.error(title + "，请选择【未过账】的数据");
        return false;
      }

      // const hasNonWaterReceiptId = this.selectedRows.every(
      //   (row) => row.waterReceiptId === this.selectedRows[0]?.waterReceiptId
      // );
      // if (!hasNonWaterReceiptId) {
      //   this.$message.error(title + "，请选择【关联申请单号】的数据");
      //   return false;
      // }

      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      // 提取 `/profile/upload/...` 之后的部分
      const fullPath = response.url;
      const relativePath = fullPath.substring(fullPath.indexOf("/profile/upload"));
      this.formUpload.waterBillImg = relativePath;
      // 触发上传成功事件
      this.$emit("upload-success");
    },
    //上传水单取消按钮
    cancel() {
      this.openUpload = false;
      this.$refs.upload.clearFiles();
      this.reset();
    },

    //锁定付款
    handleIslock() {
      if (!this.checkIsDelete()) {
        return;
      }
      if (!this.checkLockStatus("锁定付款")) {
        return;
      }
      const paymentVoucherIds = this.ids;
      tagLockPaymentVoucher(paymentVoucherIds).then((response) => {
        this.getPaymentMasterList();
        this.$modal.msgSuccess("锁定付款成功!");
      });
    },
    //检查是否都是审核中
    checkLockStatus(title) {
      const hasNonPaymentVoucherStatus = this.selectedRows.some(
        (row) => row.paymentVoucherStatus !== "1"
      );
      if (hasNonPaymentVoucherStatus) {
        this.$message.error(title + "，请选择【未过账】的数据");
        return false;
      }
      return true;
    },
  },
};
</script>
